//
//  MainViewController.m
//  Browser
//
//  Created by eric on 10/23/14.
//  Copyright (c) 2014 eric. All rights reserved.
//

#import "MainViewController.h"

@interface MainViewController ()

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self loadUIWebView];
    dbManger = [DBManager getSharedInstance];
    // Do any additional setup after loading the view.
    
}




- (void) loadUIWebView
{
    CGRect frame = self.view.frame;
       
    self.btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 50, 50)];
    [self.btnBack addTarget:self action:@selector(buttonBack:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnBack setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btnBack setImage:[UIImage imageNamed:@"left.png"] forState:UIControlStateNormal];
    
    
    self.btnForward = [[UIButton alloc] initWithFrame:CGRectMake(50, 20, 50, 50)];
    [self.btnForward setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btnForward addTarget:self action:@selector(buttonForward:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnForward setImage:[UIImage imageNamed:@"right.png"] forState:UIControlStateNormal];
    
    self.btnReload = [[UIButton alloc] initWithFrame:CGRectMake(100, 20, 50, 50)];
    [self.btnReload setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btnReload addTarget:self action:@selector(buttonReload:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnReload setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];

    
    self.txtWebSite = [[UITextField alloc] initWithFrame:CGRectMake(150, 20, frame.size.width - 200, 50)];
    [self.txtWebSite  setBorderStyle:UITextBorderStyleRoundedRect];
    self.txtWebSite.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.txtWebSite.returnKeyType = UIReturnKeyGo;
    self.txtWebSite.delegate = self;

    
    self.btnGo = [[UIButton alloc] initWithFrame:CGRectMake(frame.size.width-50, 20, 50, 50)];
    [self.btnGo setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btnGo addTarget:self action:@selector(buttonGo:) forControlEvents:UIControlEventTouchUpInside];
    self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.indicator.center = CGPointMake(25, 25);
    [self.btnGo addSubview:self.indicator];
    [self.btnGo setImage:[UIImage imageNamed:@"go.png"] forState:UIControlStateNormal];
    
    
    self.btnHome = [[UIButton alloc] initWithFrame:CGRectMake(0, 70, 50, 50)];
    [self.btnHome addTarget:self action:@selector(buttonHome:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnHome setImage:[UIImage imageNamed:@"home.png"] forState:UIControlStateNormal];
    
    
    self.btnListImage = [[UIButton alloc] initWithFrame:CGRectMake(50, 70, 50, 50)];
    [self.btnListImage addTarget:self action:@selector(buttonListImage:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnListImage setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btnListImage setTitle:@"L" forState:UIControlStateNormal];
    
    self.btnTest = [[UIButton alloc] initWithFrame:CGRectMake(100, 70, 50, 50)];
    [self.btnTest addTarget:self action:@selector(buttonTest:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnTest setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btnTest setTitle:@"test" forState:UIControlStateNormal];
    
    
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 120, frame.size.width, frame.size.height-50-20)];
    self.webView.delegate = self;
    self.txtWebSite.text = @"www.sohu.com";
   
   
    // double tap
    UITapGestureRecognizer *double_tap_recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    double_tap_recognizer.numberOfTapsRequired = 2;
    double_tap_recognizer.delegate = self;
    [self.webView addGestureRecognizer : double_tap_recognizer];

    
    [self.view addSubview:self.txtWebSite];
    [self.view addSubview:self.btnGo];
    [self.view addSubview:self.btnBack];
    [self.view addSubview:self.btnForward];
    [self.view addSubview:self.btnReload];
    [self.view addSubview:self.btnHome];
    [self.view addSubview:self.btnListImage];
    [self.view addSubview:self.btnTest];
    [self.view addSubview:self.webView];
    [self setViewRotation];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




- (void) loadURL: (NSString *) url
{
    NSMutableString *httpStr = [[NSMutableString alloc] initWithString:@"http://"];
    NSString *currentURL = [self.txtWebSite text];
    currentURL = [currentURL stringByReplacingOccurrencesOfString:@"。" withString:@"."];
    if(![currentURL hasPrefix:@"http://"])
    {
        currentURL = [NSString stringWithFormat:@"%@%@", httpStr, currentURL];
        self.txtWebSite.text = currentURL;
    }
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:currentURL]]];

}



- (void) webViewDidStartLoad:(UIWebView *)webView
{
    
    [self.indicator startAnimating];
//    [self.btnGo setTitle:@"Loading" forState:UIControlStateNormal];
}

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
    [self.indicator stopAnimating];

}

- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [self setViewRotation];
}



-(void)handleDoubleTap:(UITapGestureRecognizer *)sender{
//    CGPoint point = [sender locationInView:self.view];
    if( [sender isKindOfClass:[UITapGestureRecognizer class]])
    {
        
        CGPoint touchPoint = [sender locationInView:self.webView];
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        bool pageFlag = [userDefaults boolForKey:@"pageDirectionRTLFlog"];
        NSLog(@"pageFlag tapbtnRight %d", pageFlag);
        
        if(self.interfaceOrientation == UIInterfaceOrientationPortrait || self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
        {
            NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
            NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:imgURL];
            NSLog(@"urlToSave :%@",urlToSave);
            if( [urlToSave length] > 0)
            {
                _currentIMGURL = urlToSave;
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Do you want to serialize img?" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@"cancel", nil];
                alert.tag = 1;
                [alert show];
            }
            
        }
    }

}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (BOOL) gestureRecognizer:(UITapGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return YES;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   if( alertView.tag == 1)
   {
      if (buttonIndex == 0)
      {
         //Code for OK button
         NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(saveImage) object:nil];
         [thread start];
      }
      if (buttonIndex == 1)
      {
         //Code for download button
      }
   }else if  (alertView.tag == 2)
   {
      if (buttonIndex == 0)
      {
         NSString *pinStr = [[alertView textFieldAtIndex:0] text];

         if( [pinStr isEqualToString:@"m"]){
            PhotoViewController *photoView = [[PhotoViewController alloc] initWithNibName:nil bundle:nil];
            [self presentViewController:photoView animated:YES completion:nil];
         }
      }
   }
   
}

-(void) saveImage
{
   
   //         UIImage *image = [UIImage imageWithData:imageData];
//   BOOL ret = [dbManger insertImage:_currentIMGURL mainUrl:imageData];
      [self performSelectorOnMainThread:@selector(insertImageToDB) withObject:nil waitUntilDone:NO];
   
}

- (void) insertImageToDB
{
   NSURL *imageURL = [NSURL URLWithString:_currentIMGURL];
//   NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

    [self downloadImageWithURL:imageURL completionBlock:^(BOOL succeeded, NSData *imageData) {
        if (succeeded) {
            BOOL ret = [dbManger insertImage:_currentIMGURL mainUrl:imageData];
            if(!ret)
            {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Insert Failed" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
        }else
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Download Failed" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
}

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *imageData))completionBlock
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if ( !error )
                               {
//                                   UIImage *image = [[UIImage alloc] initWithData:data];
                                   completionBlock(YES,data);
                               } else{
                                   completionBlock(NO,nil);
                               }
                           }];
}

- (void) setViewRotation
{
    CGRect frame = self.view.frame;
    CGFloat longSide = frame.size.width > frame.size.height? frame.size.width : frame.size.height;
    CGFloat shortSide = frame.size.width < frame.size.height? frame.size.width : frame.size.height;

    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    if( UIInterfaceOrientationIsLandscape(orientation))
    {
        NSLog(@"landscape");
        self.btnBack.frame = CGRectMake(0, 20, 50, 50);
        self.btnForward.frame = CGRectMake(50, 20, 50, 50);
        self.btnReload.frame = CGRectMake(100, 20, 50, 50);
        self.txtWebSite.frame = CGRectMake(150, 20, longSide-200, 50);
        self.btnGo.frame = CGRectMake(longSide-50, 20, 50, 50);
        self.btnHome.frame = CGRectMake(0, 70, 50, 50);
        self.btnListImage.frame = CGRectMake(50, 70, 50, 50);
        self.btnTest.frame = CGRectMake(100, 70, 50, 50);
        self.webView.frame = CGRectMake(0, 120, longSide, shortSide - 70);
        
    }else
    {
        NSLog(@"portrait");
        self.btnBack.frame = CGRectMake(0, 20, 50, 50);
        self.btnForward.frame = CGRectMake(50, 20, 50, 50);
        self.btnReload.frame = CGRectMake(100, 20, 50, 50);
        self.txtWebSite.frame = CGRectMake(150, 20, shortSide-200, 50);
        self.btnGo.frame = CGRectMake(shortSide-50, 20, 50, 50);
        self.btnHome.frame = CGRectMake(0, 70, 50, 50);
        self.btnListImage.frame = CGRectMake(50, 70, 50, 50);
        self.btnTest.frame = CGRectMake(100, 70, 50, 50);
        self.webView.frame = CGRectMake(0, 120, shortSide, longSide - 70);
    }

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction) buttonGo:(id)sender
{
    [self.indicator stopAnimating];
    [self loadURL:[self.txtWebSite text]];
}

- (IBAction) buttonBack:(id)sender
{
    [self.indicator stopAnimating];
    [self.webView goBack];
}

- (IBAction) buttonForward:(id)sender
{
    [self.indicator stopAnimating];
    [self.webView goForward];
}

- (IBAction) buttonReload:(id)sender
{
    [self.indicator stopAnimating];
    [self.webView reload];
}

- (IBAction) buttonHome:(id)sender
{
    [self.indicator stopAnimating];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
}

- (IBAction) buttonListImage:(id)sender
{
//    ImageViewController *imgView = [[ImageViewController alloc]initWithNibName:nil bundle:nil];
//   
//    [self presentViewController:imgView animated:YES completion:nil];
   
}

- (IBAction) buttonTest:(id)sender
{
   UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Pin Screen" message:@"Please input PIN!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:@"cancel", nil];
   alert.alertViewStyle = UIAlertViewStylePlainTextInput;
   alert.tag = 2;
   [alert show];

   
}

- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
    [self.txtWebSite resignFirstResponder];
    [self.indicator stopAnimating];
    [self loadURL:[self.txtWebSite text]];
    return YES;
}

@end
